package com.dmw.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dmw.reggie.common.BaseContext;
import com.dmw.reggie.entity.*;
import com.dmw.reggie.mapper.OrdersMapper;
import com.dmw.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Resource
    private AddressBookService addressBookService;

    @Resource
    private ShoppingCartService shoppingCartService;

    @Resource
    private UserService userService;

    @Resource
    private OrderDetailService orderDetailService;

    @Override
    public void submit(Orders orders) {

        // 获取用户id
        Long currentId = BaseContext.getCurrentId();
        orders.setUserId(currentId);

        // 生成订单id
        long orderId = IdWorker.getId();

        // 查询用户数据
        User user = userService.getById(currentId);

        // 查询该单购物情况
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        // 查询用户默认地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        AtomicInteger amount = new AtomicInteger(0);

        // 遍历购物结果，得到总金额和订单明细
        List<OrderDetail> orderDetails = new ArrayList<>();
        shoppingCarts.forEach(i -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(i, orderDetail, "id");
            orderDetail.setOrderId(orderId);
            amount.addAndGet(i.getAmount().multiply(new BigDecimal(i.getNumber())).intValue());
            orderDetails.add(orderDetail);
        });

        // 设置订单id
        orders.setId(orderId);
        // 设置订单号
        orders.setNumber(String.valueOf(orderId));
        // 设置结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        // 设置电话
        orders.setPhone(addressBook.getPhone());
        // 设置收件人
        orders.setConsignee(addressBook.getConsignee());
        // 设置实收金额
        orders.setAmount(new BigDecimal(amount.get()));
        // 设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 设置状态
        orders.setStatus(2);
        // 设置用户名
        orders.setUserName(user.getName());
        // 设置地址
        orders.setAddress((addressBook.getProvinceName() == null? "": addressBook.getProvinceName())
                + (addressBook.getCityName() == null? "": addressBook.getCityName())
                + (addressBook.getDetail() == null? "": addressBook.getDetail()));

        // 向订单表插入数据
        this.save(orders);

        // 向订单明细表插入数据
        orderDetailService.saveBatch(orderDetails);

        // 清空购物车
        shoppingCartService.remove(queryWrapper);

    }
}
